package com.doudou.zuul.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {


    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String doGet(String url, List<NameValuePair> param) throws Exception {
        String result = null;
        //请求地址
        //获取请求参数
        //获取httpclient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet = null;
            if (param != null && param.size() != 0) {
                String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(param));
                //拼接参数
                StringBuffer sb = new StringBuffer();
                sb.append(url);
                sb.append("?");
                sb.append(paramStr);
                httpGet = new HttpGet(sb.toString());
            } else {
                httpGet = new HttpGet(url);
            }
            // 设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000).setConnectTimeout(5000).build();
            httpGet.setConfig(requestConfig);
            // 提交参数发送请求
            response = httpclient.execute(httpGet);

            // 得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            // 判断响应信息是否正确
            if (statusCode != HttpStatus.SC_OK) {
                // 终止并抛出异常
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
            EntityUtils.consume(entity);
        } finally {
            //关闭所有资源连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result.toString();

    }


    public static String doPostKeyValue(String url, Map<String, String> map) {
        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //创建post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            // 设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(200000).setConnectTimeout(5000000)
                    .build();
            httpPost.setConfig(requestConfig);
            List<NameValuePair> param = new ArrayList<>();
            if (map != null && map.size() != 0) {
                map.keySet().stream().forEach(t -> {
                    param.add(new BasicNameValuePair(t, map.get(t)));
                });
            }
            if (!CollectionUtils.isEmpty(param)) {
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(param, "utf-8");
                httpPost.setEntity(urlEncodedFormEntity);
            }
            response = httpclient.execute(httpPost);
            // 得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            // 判断响应信息是否正确
            if (statusCode == HttpStatus.SC_OK) {
                // 终止并抛出异常
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    //result = EntityUtils.toString(entity);//不进行编码设置
                    result = EntityUtils.toString(entity, "UTF-8");
                }
                EntityUtils.consume(entity);
            } else {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭所有资源连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPostJsonBody(String url, String body) {
        //创建一个信任的连接
        CloseableHttpClient httpClient = createSSLInsecureClient();
        //发送请求的实体类
        HttpPost httpPost = new HttpPost(url);
        String result = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(4000).setConnectTimeout(6000)
                    .build();
            httpPost.setConfig(requestConfig);
            //这个是设置请求的类型，这个可能需要重点注意下，需要看对方接收的是什么
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setEntity(new StringEntity(body));
            //发送请求
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            // 判断响应信息是否正确
            if (statusCode != HttpStatus.SC_OK) {
                // 终止并抛出异常
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + "utf-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException("读取流文件异常", e);
        } catch (Exception e) {
            throw new RuntimeException("通讯未知系统异常", e);
        }
        return result;
    }

    /**
     * 创建一个SSL信任所有证书的httpClient对象
     *
     * @return
     */
    public static CloseableHttpClient createSSLInsecureClient() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 默认信任所有证书
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
            // AllowAllHostnameVerifier: 这种方式不对主机名进行验证，验证功能被关闭，是个空操作(域名验证)
            SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return HttpClients.custom().setSSLSocketFactory(sslcsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        //如果创建失败，就创建一个默认的Http的连接
        return HttpClients.createDefault();
    }


    /**
     * 无需本地证书keyStore的SSL https带参数请求
     * post K - V 格式的数据
     *
     * @param url
     * @return
     */
    public static String postSSLParams(String url, String body) {
        //创建一个信任的连接
        CloseableHttpClient httpClient = createSSLInsecureClient();
        //发送请求的实体类
        HttpPost httpPost = new HttpPost(url);
        //接收返回值
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000).setConnectTimeout(5000)
                    .build();
            httpPost.setConfig(requestConfig);
            //这个是设置请求的类型，这个可能需要重点注意下，需要看对方接收的是什么
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setEntity(new StringEntity(body));
            //发送请求
            HttpResponse response = httpClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            // 判断响应信息是否正确
            if (statusCode != HttpStatus.SC_OK) {
                // 终止并抛出异常
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            //接收返回值
            HttpEntity httpEntity = response.getEntity();

            //返回值处理
            br = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "utf-8"));
            String s = null;
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + "utf-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException("读取流文件异常", e);
        } catch (Exception e) {
            throw new RuntimeException("通讯未知系统异常", e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    public static String postSSLParams2(String url, String body) {
        //创建一个信任的连接
        CloseableHttpClient httpClient = createSSLInsecureClient();
        //发送请求的实体类
        HttpPost httpPost = new HttpPost(url);
        //接收返回值
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(6000).setConnectTimeout(8000)
                    .build();
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setEntity(new StringEntity(body));
            HttpResponse response = httpClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            //接收返回值
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                //返回值处理
                br = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "utf-8"));
                String s = null;
                while ((s = br.readLine()) != null) {
                    sb.append(s);
                }
            } else {
                return "SUCCESS";
            }
            return sb.toString();
        } catch (Exception e) {
            LOGGER.info("{}", e);
            return "FAIL";
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
